package com.coldchain.authclient.interceptor;

import com.coldchain.authclient.config.ServiceAuthConfig;
import com.coldchain.authclient.config.UserAuthConfig;
import com.coldchain.authclient.jwt.ServiceAuthUtil;
import com.coldchain.common.constant.RestCodeConstants;
import com.fangliai.core.context.BaseContextHandler;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
/**
 * okhttp 拦截器自动设置okhttp请求头
 * @ClassName OkHttpTokenInterceptor
 * @Author fangliai
 * @Date 2018/8/30 9:49
 * @Vesion 1
 **/
public class OkHttpTokenInterceptor implements Interceptor {
	private final static Logger log= LoggerFactory.getLogger(OkHttpTokenInterceptor.class);
	@Autowired
	@Lazy
	private ServiceAuthUtil serviceAuthUtil;
	@Autowired
	@Lazy
	private ServiceAuthConfig serviceAuthConfig;
	@Autowired
	@Lazy
	private UserAuthConfig userAuthConfig;


	@Override
	public Response intercept(Chain chain) throws IOException {
		Request newRequest = chain.request()
				.newBuilder()
				//添加用户的token
				.header(userAuthConfig.getTokenHeader(), BaseContextHandler.getToken())
				.build();
		Response response = chain.proceed(newRequest);
		/**
		 * FORBIDDEN 403权限检查失败.刷新权限,并重式
		 */
		if(HttpStatus.OK.value()!=response.code()){
		    //TODO  全局异常返回出错导致
			if(response.body().string().contains(String.valueOf(RestCodeConstants.EX_CLIENT_INVALID_CODE))){
				log.info("Client Token Expire,Retry to request...");
				serviceAuthUtil.refreshClientToken();
				newRequest = chain.request()
						.newBuilder()
						.header(userAuthConfig.getTokenHeader(), BaseContextHandler.getToken())
						.header(serviceAuthConfig.getTokenHeader(),serviceAuthUtil.getClientToken())
						.build();
				response = chain.proceed(newRequest);
			}
		}
	    return response;
	}

}
